package rudia.org.core.spring;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import rudia.org.core.RuMap;
import rudia.org.core.Rutil;


public class RudiaInterceptor extends HandlerInterceptorAdapter {


	@SuppressWarnings("rawtypes")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		/*
		 * ====================================== Values Binding Process =====================================
		 */

		// if (ServletFileUpload.isMultipartContent(request)) {// 첨부파일이면...
		//
		//
		// MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		//
		// if (multipartRequest != null) {
		// MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
		//
		// Iterator<String> iter = fileMap.keySet().iterator();
		//
		// }
		//
		// } else {

		/* 1.form values 바인딩 */
		HashMap<String, Object> form = new HashMap<String, Object>();
		String[] value = null;
		int valueSize = 0;

		Map param = (Map) request.getParameterMap();

		Iterator iter = param.keySet().iterator();

		while (iter.hasNext()) {
			String key = (String) iter.next();
			value = (String[]) param.get(key);
			valueSize = value.length;
			if (valueSize == 1) {// 한건(배열형으로 담기지 않게 하기 위한 처리
				for (int validx = 0; validx < value.length; validx++) {
					form.put(key, value[validx]);// = form.put(key, value[0]);
				}
			} else {// 배열
				form.put(key, value);
			}
		}

		/* 2.session values 바인딩 */
//		LoginVO loginVO = SessionUtil.getLoginVO(request);
//		if (loginVO != null) {
//			// ---------------------DB에 저장될 값만 담는다. 그외는 loginVO에서 찾아 쓸수 있다.(main/view 참고)
//			form.put("reg_user_seq", loginVO.getReg_user_seq());
//			form.put("updt_user_seq", loginVO.getUpdt_user_seq());
//			form.put("s_user_nm", loginVO.getUser_nm());
//		}
//
//		Rudia prjVO = (Rudia) request.getSession().getAttribute("prjVO");
//		if (prjVO != null) {
//			if (form.get("prj_seq")==null||form.get("prj_seq")=="") {
//				form.put("prj_seq", prjVO.get("prj_seq"));
//				form.put("prj_cd", prjVO.get("prj_cd"));
//				form.put("prj_nm", prjVO.get("prj_nm"));
//			}
//			form.put("s_obs_seq", prjVO.get("obs_seq"));
//			form.put("s_obs_cd", prjVO.get("obs_cd"));
//			form.put("s_obs_nm", prjVO.get("obs_nm"));
//			form.put("s_up_obs_seq", prjVO.get("up_obs_seq"));
//			form.put("s_up_obs_nm", prjVO.get("up_obs_nm"));
//			form.put("s_chrg_job_cd", prjVO.get("chrg_job_cd"));
//			form.put("s_max_fbs_seq", prjVO.get("max_fbs_seq"));
//
//		}
		
		
		form.put("z_URL", request.getRequestURL()); // URL
		form.put("z_Locale", request.getLocale()); // URL
		form.put("z_LocalName", request.getLocalName()); // URL
		form.put("z_getRequestedSessionId", request.getRequestedSessionId()); // URL
		form.put("z_clientIP", request.getRemoteAddr()); // URL
		// form.put("z_URI", request.getRequestURI()); // URL
		// form.put("z_getLocalAddr", request.getLocalAddr()); // URL
		// form.put("z_getLocalPort", request.getLocalPort()); // URL
		
		form.put("z_clientOS", Rutil.getClntOsInfo(request)); // URL
		form.put("z_clientWebKind", Rutil.getClntWebKind(request)); // URL
		form.put("z_user-agent", request.getHeader("user-agent")); // URL
		

		/* 3.return 변수 생성 */
		RuMap<String, Object> rumap = new RuMap<String, Object>();
		rumap.putAll(form);
		// ============================== 이하 form 대신 rudia 변수를 사용한다.

		/*
		 * ===================================== Common Business Process =====================================
		 */

		/* Tree변수초기화 */
		if (rumap.get("parentid") == null || "".equals(rumap.get("nodeid"))) {
			rumap.put("nodeid", "0");
			rumap.put("n_level", "0");
		}

		/*
		 * ==================== Binding 된 값을 출력하고 [rudia] 에 담아 return 한다. ===================
		 */
		if (Rutil.log.isDebugEnabled()) {
			// log.debug("mkModel.toStringKey() : " + mkModel.toStringKey());
			Rutil.log.debug("rudia.toStringAll() By RudiaInterceptor : " + rumap.toStringAll());
		}
		request.setAttribute("rumap", rumap);
		// }
		return true;

	}

	@SuppressWarnings("rawtypes")
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

		RuMap rumap = (RuMap) request.getAttribute("rumap");
		Rutil.log.info("★★★★ "+(String)rumap.get("prj_nm")+" / "+(String)rumap.get("s_user_nm")+" / "+(String)rumap.get("z_LocalName")+" / "+(String)rumap.get("z_clientIP")+" / "+((StringBuffer)rumap.get("z_URL")).toString()+"\n\n");

	}

}